import React, { useState, useEffect } from "react";
import { NavLink, useLocation, useNavigate } from 'react-router-dom'
import "./index.scss";
import { Checkbox, Popup, PickerView, DatePickerView, Button, Toast } from "antd-mobile";
import { IAddress } from '../../interface'
import API from '../api/address'
import { store } from '../../store'
import { EnvironmentOutline, RightOutline, LeftOutline } from 'antd-mobile-icons'
import { useDispatch, useSelector } from "react-redux";
import { SET_ORDER_ADDRESS, SET_ORDER } from '../../store/actionType'
import API_ORDER from "../api/order";

const initItem = {
  address_city: '',
  address_contacts: '',
  address_phone: '',
  address_town: '',
  _id: '',
  user_id: ''
}
const labelRenderer = (type: string, data: number) => {
  switch (type) {
    case 'year':
      return data + '年'
    case 'month':
      return data + '月'
    case 'day':
      return data + '日'
    case 'hour':
      return data + '时'
    case 'minute':
      return data + '分'
    case 'second':
      return data + '秒'
    default:
      return data
  }
}
function formatDateTime(date: any) {
  var y = date.getFullYear();
  var m = date.getMonth() + 1;
  // m = m < 10 ? ('0' + m) : m;
  var d = date.getDate();
  // d = d < 10 ? ('0' + d) : d;
  var h = date.getHours();
  var minute = date.getMinutes();
  minute = minute < 10 ? ('0' + minute) : minute;
  return y + '-' + m + '-' + d + ' ' + h + ':' + minute;
  return y + '-' + m + '-' + d
};
const now = new Date()
export default function Total() {
  const navigate = useNavigate()
  const location = useLocation()
  const dispatch = useDispatch()
  const { orderReducer } = useSelector((state: any) => state)
  // console.log(location, 'location')
  const fee = location.state.total < 100 ? 10.00 : (location.state.total > 100 && location.state.total < 200 ? 20.00 : (location.state.total > 200 && location.state.total < 300 ? 30.00 : (location.state.total > 300 && location.state.total < 400 ? 40.00 : (location.state.total > 400 && location.state.total < 500 ? 50.00 : 100.00))))
  const [address, setAddress] = useState<IAddress[]>([])
  const [visible, setVisible] = useState(false)
  const [visible1, setVisible1] = useState(false)
  const { _id, token } = store.getState().userReducer.user
  const [isCheck, setIsCheck] = useState<boolean>(true)
  const [addressList, setAddressList] = useState<IAddress>(initItem)
  const [value, setValue] = useState<Date>(now)
  const [times, setTimes] = useState<string>('')
  const [timesList, setTimesList] = useState<string>('配送时间')
  const getAddress = async () => {
    let res = await API['getAddress']({ _id, token })
    console.log(res, '获取地址')
    setAddress(res.data.data)
  }
  useEffect(() => {
    getAddress()
  }, [])
  const changeCheck = (val: boolean) => {
    setIsCheck(val)
  }
  const changeCheck1 = (val: boolean) => {
    setIsCheck(!val)
  }
  const changeTime = (val: any) => {
    // console.log(val)
    setTimes(formatDateTime(val))
  }
  const order = async () => {
    let res = await API_ORDER['orderAdd']({ goods: location.state.items, token, total: location.state.total - fee })
    console.log(res, '下单成功')
    dispatch({ type: SET_ORDER, payload: {order_id:res.data.data._id,goods: location.state.items, total: location.state.total - fee} })
  }
  return (
    <div>
      <Popup visible={visible}
        onMaskClick={() => {
          setVisible(false)
        }}
        bodyStyle={{
          borderTopLeftRadius: '8px',
          borderTopRightRadius: '8px',
          minHeight: '40vh',
        }}>
        {
          address.length ? address.map((item: IAddress) => <div key={item._id}>
            <div className='location'>
              <article onClick={() => {
                dispatch({ type: SET_ORDER_ADDRESS, payload: { city: item.address_city, town: item.address_town, contacts: item.address_contacts, phone: item.address_phone } })
                setAddressList(item)
                setVisible(false)
              }}>
                <i><EnvironmentOutline /></i>
                <h2>{item.address_city} {item.address_town}</h2>
              </article>
              <aside>{item.address_contacts} {item.address_phone}</aside>
              <b><RightOutline /></b>
            </div>
          </div>) : <div className='noAddress'>
            <i><EnvironmentOutline /></i>
            <h1>还没有任何配送地址</h1>
            <div className='address_go' onClick={() => {
              navigate('/pushAddress')
            }}>新增地址</div>
          </div>
        }
      </Popup>
      <div className='order_back1'>
        <Button onClick={() => navigate(-1)}><LeftOutline /></Button>
        订单确认
      </div>
      <div className="delivery">

        {/* <div onClick={() => {
          setVisible(true)
        }}>{Object.values(addressList)[0]!='' ? <div className="location_p"><hgroup>{addressList.address_city} {addressList.address_town}</hgroup><aside>{addressList.address_contacts} {addressList.address_phone}</aside><b><RightOutline /></b></div> : <span>请选择收货地址<i><RightOutline /></i></span>}</div> */}
        <div onClick={() => {
          setVisible(true)
        }}>{orderReducer.order_address.city != '' ? <div className="location_p"><hgroup>{orderReducer.order_address.city} {orderReducer.order_address.town}</hgroup><aside>{orderReducer.order_address.contacts} {orderReducer.order_address.phone}</aside><b><RightOutline /></b></div> : <span>请选择收货地址<i><RightOutline /></i></span>}</div>
        <ul>
          <li>配送方式</li>
          <li>
            <span>21cake配送</span>
            <Checkbox checked={isCheck} onChange={changeCheck}></Checkbox>
          </li>
          <li>
            <span>站点自提</span>
            <Checkbox checked={!isCheck} onChange={changeCheck1}></Checkbox>
          </li>
        </ul>
        <div onClick={() => {
          setVisible1(true)
        }}><span >{timesList}<i><RightOutline /></i></span></div>
        <Popup visible={visible1}
          onMaskClick={() => {
            setVisible1(false)
          }}
          bodyStyle={{
            borderTopLeftRadius: '8px',
            borderTopRightRadius: '8px',
            minHeight: '40vh',
          }}>
          <div className="date_time"><span onClick={() => (setTimes(''), setVisible1(false))}>取消</span><span>配送时间</span><span onClick={() => (setVisible1(false), setTimesList(times))}>确定</span></div>
          <DatePickerView
            value={value}
            onChange={changeTime}
            defaultValue={now}
            mouseWheel={true}
            precision='hour'
            renderLabel={labelRenderer}
          // filter={dateFilter}
          />
        </Popup>

      </div>
      {location.state.items.map((ele: any) => <div key={ele._id} className="shopping">
        <img
          src={ele.img}
          alt=""
        />
        <ul>
          <li>￥{ele.price}</li>
          <li>
            <p>{ele.goods_name}</p>
            <p>
              规格： 180（2瓶） <span>X{ele.count}</span>
            </p>
            {ele.cutlery ? <p>含{ele.cutlery[1]}套{ele.cutlery[0]}</p> : <p>含2套餐具</p>}
          </li>
        </ul>
      </div>)}
      <div className="shop">



      </div>

      <div className="coupons">
        <p onClick={() => {

        }}>优惠卷/尊享卡 <span><em>0</em>张可用</span></p>
      </div>

      <div className="count">
        <p>共<b>{location.state.items.length}</b>件商品</p>
        <p>商品金额<span>&yen;{location.state.total}</span></p>
        {/* <p>配送费<span>&yen;{location.state.express||0.00}</span></p> */}
        <p>配送费<span>&yen;{fee}</span></p>
        <p>小计<span>&yen;{location.state.total - fee}</span></p>
        <p>商品金额<span>￥{location.state.total}</span></p>
        

      </div>
      <div className="comment">
        <div>
          <h5>备注</h5>
          <p>请输入你的特殊要求，200字以内</p>
        </div>
        <div>
          <h5>发票</h5>
          <p>订单支付后，可申请发票</p>
        </div>
      </div>

      <div className="close">
        <p>
          <span>共<b>{location.state.items.length}</b>合计：<strong>&yen;{location.state.total - fee}</strong>
          </span>
          <Button onClick={() => {
            if (orderReducer.order_address.city == '') {
              Toast.show({
                content: '请选择配送地址',
                position: 'top'
              })
            } else if (timesList == '配送时间') {
              Toast.show({
                content: '请选择配送时间',
                position: 'top'
              })
            } else {
              order()
              navigate('/pay')
            }
          }}>下单</Button>

        </p>
      </div>


    </div>
  );
}
